#include "GeoCoordinate.h"
#include <QtCore>

static qreal PI = 3.14159265358979323846;
static qreal R = 6371.009; // km

qreal toRad(qreal a) {
    return a * PI / 180;
}

qreal toDeg(qreal a) {
    return a * 180 / PI;
}

void GeoCoordinate::referenceChanged(double r_lat, double r_long)
{
    // distance
    qreal dLat = toRad(r_lat - q_coord.latitude());
    qreal dLon = toRad(r_long - q_coord.longitude());
    qreal a = qSin(dLat/2) * qSin(dLat/2) +
            qCos(toRad(q_coord.latitude())) * qCos(toRad(r_lat)) *
            qSin(dLon/2) * qSin(dLon/2);
    qreal c = 2 * qAtan2(qSqrt(a), qSqrt(1-a));
    _distance = R * c;

    // bearing
    qreal y = qSin(dLon) * qCos(r_lat);
    qreal x = qCos(q_coord.latitude()) * qSin(r_lat) -
            qSin(q_coord.latitude()) * qCos(r_lat) * qCos(dLon);
    _bearing = toDeg(qAtan2(y, x));

    emit distanceChanged();
}

void GeoCoordinate::referenceChanged(const QGeoCoordinate& r_coord)
{
    double temp;
    bool toEmit = false;
    temp = r_coord.distanceTo(q_coord);
    if(_distance != temp) {
        _distance = temp;
        toEmit = true;
    }
    temp = r_coord.azimuthTo(q_coord);
    if(_bearing != temp) {
        _bearing = temp;
        toEmit = true;
    }
    if(toEmit)
        emit distanceChanged();
    //qDebug() << "Yeee: " << r_coord.toString();
}
